package cc.liyinghao.controller;


import cc.liyinghao.common.api.Result;
import cc.liyinghao.param.SendMessageParam;
import cc.liyinghao.service.WebSocketService;
import cn.hutool.json.JSONObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Base64;

@RestController
@Slf4j
@RequestMapping("/file")
@RequiredArgsConstructor
@Api(tags = "文件路由")
public class FileController {

    private final WebSocketService webSocketService;

    @GetMapping("/send_file")
    @ApiOperation(value = "发送文件")
    public Result<String> sendFile(SendMessageParam message) {
        webSocketService.sendFileToUser(message.getMsgContent(), String.valueOf(message.getTargetId()));
        return Result.success();
    }

    /**
     * 上传图片并转发给某个在线用户
     */
    @PostMapping("/uploadImage")
    public ResponseEntity<String> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("from") String fromUser,
            @RequestParam("to") String toUser) {
        try {
            // 读取文件为 Base64
            byte[] bytes = file.getBytes();
            String base64 = "data:" + file.getContentType() + ";base64," +
                    Base64.getEncoder().encodeToString(bytes);

            File dest = new File("C:\\Users\\35687\\Desktop\\java测试\\File\\" + file.getOriginalFilename());

//            // 获取目标用户的 WebSocket Channel
//            Channel toChannel = WebSocketHandler.getChannel(toUser);
//            if (toChannel != null && toChannel.isActive()) {
//                toChannel.writeAndFlush(new TextWebSocketFrame(imageMsg.toJSONString()));
//                return ResponseEntity.ok("发送成功");
//            } else {
//                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("目标用户不在线");
//            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("发送失败");
        }
    }
}
